﻿using NetWing.BPM.Core;
using NetWing.BPM.Core.Bll;
using NetWing.BPM.Core.Dal;
using NetWing.BPM.Core.Model;
using NetWing.Common;
using NetWing.Common.Data;
using NetWing.Common.Data.SqlServer;
using NetWing.Model;
using Newtonsoft.Json.Linq;
using Senparc.Weixin.MP.AdvancedAPIs.TemplateMessage;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using static NetWing.BPM.Admin.JydModleOrder.ashx.ajax_submit;

namespace NetWing.BPM.Admin.JydflowTasktemplate
{
    public class templateflow
    {
        public static bool CreateInstance(JObject obj)
        {
            SqlTransaction ctran = SqlHelper.BeginTransaction(SqlEasy.connString);//取得一个事务
            var flowInstance = obj.ToObject<JydflowtasklistModel>();
            //获取提交的表单数据
            var frmdata = new JObject();
            foreach (var property in obj.Properties().Where(U => U.Name.Contains("data_")))
            {
                frmdata[property.Name] = property.Value;
            }
            try
            {
                //结合订单信息写任务清单
                #region 将订单写进任务表中
                JydflowtasklistModel jydflowtasklistModel = new JydflowtasklistModel
                {
                    nodename = flowInstance.nodename,
                    operatorID = flowInstance.operatorID,
                    operatorname = flowInstance.operatorname,
                    orderID = flowInstance.orderID,
                    ordername = flowInstance.ordername,
                    PrintedmatterID = flowInstance.PrintedmatterID,
                    Printedmattername = flowInstance.Printedmattername,
                    addtime = flowInstance.addtime,
                    isitcomplete = flowInstance.isitcomplete,
                    completeofth = flowInstance.completeofth,
                    orderkey = flowInstance.orderkey,
                    timestamp = flowInstance.timestamp,
                    SchemeContent = flowInstance.SchemeContent
                };
                DbUtils.tranInsert(jydflowtasklistModel, ctran);//提交流程操作记录
                ctran.Commit();//提交事务
                #endregion
                SqlTransaction tran = SqlHelper.BeginTransaction(SqlEasy.connString);//取得一个事务
                JydflowRecordModel jydflowRecordModel = new JydflowRecordModel
                {
                    processID = 0,
                    Operationalcontent = "开单",
                    Operationtime = DateTime.Now,
                    addtime = flowInstance.timestamp,
                    Operctionname = flowInstance.operatorname,
                    orderid = flowInstance.orderID,
                    Remarks = flowInstance.completeofth,
                    nikeyid = flowInstance.orderkey,
                    sortid = flowInstance.isitcomplete,
                    SchemeContent = int.Parse(flowInstance.SchemeContent)
                };
                DbUtils.tranInsert(jydflowRecordModel, tran);//提交流程操作记录
                tran.Commit();//提交事务



                //开始微信发放任务
                #region 开始发放任务
                string dt = "select * from jydflowTasktemplate where PrintedmatterID='" + flowInstance.PrintedmatterID + "' and softdeletion != 1 order by sortid asc";
                DataTable tableData = SqlEasy.ExecuteDataTable(dt);
                DataTable arrayi;
                object objjj = null;
                try
                {
                    foreach (DataRow dr in tableData.Rows)
                    {
                        if (int.Parse(dr["priority"].ToString()) == 1)
                        { //如果优先级等于1就发送带超链接的,不等于1的就发送没有连接的
                            //为模版中的各属性赋值
                            var templateData = new ProductTemplateData()
                            {
                                first = new TemplateDataItem(flowInstance.ordername + "通知", "#66ccff"),
                                keyword1 = new TemplateDataItem("JYD" + flowInstance.orderID, "#66ccff"),
                                keyword2 = new TemplateDataItem(flowInstance.completeofth, "#66ccff"),
                                keyword3 = new TemplateDataItem(DateTime.Now.ToString("yyyy-MM-dd")),
                                keyword4 = new TemplateDataItem(dr["nodename"].ToString(), "#66ccff"),
                                keyword5 = new TemplateDataItem(dr["nodename"].ToString(), "#66ccff"),
                                remark = new TemplateDataItem("流程创建人:<" + SysVisitor.Instance.cookiesUserName + ">此任务中你所做操作<" + dr["nodename"].ToString() + ">", "#66ccff")
                            };
                            string templateid = NetWing.Common.ConfigHelper.GetValue("templageid");//从web.config 获得模板ID
                                                                                                   //通知所有员工就是openid不同
                            string str = dr["operatorname"].ToString();
                            string[] arraya = str.Split(',');
                            foreach (string i in arraya)
                            {
                                if (!string.IsNullOrEmpty(i))
                                {
                                    objjj = SqlEasy.ExecuteScalar("select OpenID from Sys_Users where UserName='" + i + "'");
                                    if (objjj != null && objjj != DBNull.Value && !string.IsNullOrEmpty(objjj.ToString()))
                                        weixin.wxhelper.sendTemplateMsg(objjj.ToString(), templateid, NetWing.Common.ConfigHelper.GetValue("website") + "/JydModleOrder/taskQRcode.aspx?keyid=" + flowInstance.orderkey + "", templateData);
                                }
                            }
                        }
                        //else
                        //{
                        //    //为模版中的各属性赋值
                        //    var templateData = new ProductTemplateData()
                        //    {
                        //        first = new TemplateDataItem(flowInstance.ordername + "通知", "#66ccff"),
                        //        keyword1 = new TemplateDataItem("JYD" + flowInstance.orderID, "#66ccff"),
                        //        keyword2 = new TemplateDataItem(flowInstance.completeofth, "#66ccff"),
                        //        keyword3 = new TemplateDataItem(DateTime.Now.ToString("yyyy-MM-dd")),
                        //        keyword4 = new TemplateDataItem(dr["nodename"].ToString(), "#66ccff"),
                        //        keyword5 = new TemplateDataItem(dr["nodename"].ToString(), "#66ccff"),
                        //        remark = new TemplateDataItem("流程创建人:<" + SysVisitor.Instance.cookiesUserName + ">此任务中你所做操作<" + dr["nodename"].ToString() + ">,此为开单通知,不需要操作", "#66ccff")
                        //    };
                        //    string templateid = NetWing.Common.ConfigHelper.GetValue("templageid");//从web.config 获得模板ID

                        //    //通知所有员工就是openid不同

                        //    string str = dr["operatorname"].ToString();
                        //    string[] arraya = str.Split(',');
                        //    foreach (string i in arraya)
                        //    {
                        //        if (!string.IsNullOrEmpty(i))
                        //        {
                        //            objjj = SqlEasy.ExecuteScalar("select OpenID from Sys_Users where UserName='" + i + "'");
                        //            if (objjj != null && objjj != DBNull.Value && !string.IsNullOrEmpty(objjj.ToString()))
                        //                weixin.wxhelper.sendTemplateMsg(objjj.ToString(), templateid,"", templateData);
                        //        }
                        //    }
                        //}
                    }
                }
                catch (Exception e)
                {
                    //写日志
                    LogModel logxq = new LogModel();
                    logxq.BusinessName = "开单成功失败";
                    logxq.OperationIp = "";
                    logxq.OperationTime = DateTime.Now;
                    logxq.PrimaryKey = "";
                    logxq.UserId = int.Parse(SysVisitor.Instance.cookiesUserId);
                    logxq.SqlText = "开单发送微信ip";
                    logxq.TableName = "jydOrder";
                    logxq.note = e.Message;
                    logxq.OperationType = (int)OperationType.Other;
                    LogDal.Instance.Insert(logxq);
                    WriteLogs.WriteLogsE("Logs", "Error >> 发送微信", e.Message + " >>> " + e.StackTrace);
                }
                #endregion
            }
            catch (Exception e)
            {
                ctran.Rollback();
                WriteLogs.WriteLogsE("Logs", "Error >> 结合订单信息写任务清单", e.Message + " >>> " + e.StackTrace);

            }

            //

            return true;
        }

        public static bool username(string VerificationOpinion, string FlowInstanceId, string VerificationFinally, string sl, string username, string keyid)

        {

            //查询
            DataRow orderid = SqlEasy.ExecuteDataRow("select * from jydorderdetail where keyid='" + keyid + "'");
            DataRow dataRow = SqlEasy.ExecuteDataRow("select * from jydflowtasktemplate where printedmattername='" + orderid["printtype"].ToString() + "' and nodename='" + username + "'");
            DataTable dataTable = SqlEasy.ExecuteDataTable("select username,openid from Sys_Users");
            Dictionary<string, string> keyValues = new Dictionary<string, string>();
            SqlTransaction sqlTransaction = SqlHelper.BeginTransaction(SqlEasy.connString);
            bool a = true;




            string user = dataRow["operatorname"].ToString();
            string[] q = user.Split(',');

            int sql;
            string r = "";
            try
            {
                foreach (string io in q)
                {
                    DataRow i = SqlEasy.ExecuteDataRow("select * from Sys_users where username ='" + io + "'");
                    //为模版中的各属性赋值
                    var templateData = new ProductTemplateData()
                    {
                        first = new TemplateDataItem(orderid["yspmc"].ToString() + "通知", "#66ccff"),
                        keyword1 = new TemplateDataItem("JYD" + orderid["orderid"].ToString(), "#66ccff"),
                        keyword2 = new TemplateDataItem("你要完成" + username, "#66ccff"),
                        keyword3 = new TemplateDataItem(DateTime.Now.ToString("yyyy-MM-dd"), "#66ccff"),
                        remark = new TemplateDataItem("此任务中你所做操作<" + username + ">,请尽快完成!备注:" + VerificationOpinion, "#66ccff")
                    };
                    string templateid = NetWing.Common.ConfigHelper.GetValue("templageid");//从web.config 获得模板ID
                                                                                           //通知所有员工就是openid不同
                    r = NetWing.BPM.Admin.weixin.wxhelper.sendTemplateMsg(i["openid"].ToString(), templateid, NetWing.Common.ConfigHelper.GetValue("website") + "/JydModleOrder/taskQRcode.aspx?keyid=" + keyid + "", templateData);
                   
                }
                if (r == "请求成功")
                {


                    sql = DbUtils.tranExecuteNonQuery("update jydflowtasklist set isitcomplete='" + dataRow["sortid"].ToString() + "',addtime='"+DateTime.Now+ "',completeofth=completeofth+'," + VerificationOpinion+":"+sl+"' where orderkey='" + orderid["omainid"].ToString() + "'", sqlTransaction);
                    JydflowRecordModel jydflowRecordModel = new JydflowRecordModel
                    {
                        Operationalcontent = username,
                        Operationtime = DateTime.Now,
                        Operctionname = CookieHelper.GetCookie("currentUserName"),
                        orderid = orderid["orderid"].ToString(),
                        Remarks = VerificationOpinion,
                        nikeyid = Convert.ToInt32(orderid["omainid"].ToString()),
                        sortid = Convert.ToInt32(dataRow["sortid"].ToString()),
                        sl = Convert.ToInt32(sl),
                        SchemeContent = Convert.ToInt32(keyid)
                    };
                    DbUtils.tranInsert(jydflowRecordModel, sqlTransaction);

                    sqlTransaction.Commit();


                }
            }
            catch (Exception e)
            {
                sqlTransaction.Rollback();
                a = false;
                return a;
            }
            return a;
        }
    }
}